package divinity.facebook
{
	import divinity.user.User;
	import divinity.user.UserTypes;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.external.ExternalInterface;
	
	public class ConnectFB extends EventDispatcher
	{
		private var app_id:Number;		
		private var _logged:Boolean;
		private var _met:String;
		private var log="";;
		public function get LOG()
		{
			return log;
		}
		public function ConnectFB(appid:String=null) 
		{
			super();
			if(appid!=null)
			{
				trace("CONNECTING");
				connect(appid);
			}
			else
			{
				trace("NOTHING");
				
			}
			log+="FB CREATED  ";
			dispatchEvent(new Event(Event.CHANGE))
		}
		public function connect(appid:String)
		{
			
			if(ExternalInterface.available)
			{
				
				ExternalInterface.addCallback("sendToFlash",FBResponse);
				ExternalInterface.call("initFB", appid);
			}
			else
			{
				trace("no");
				User.logout();
			}
			log+="CONNECT ";
			dispatchEvent(new Event(Event.CHANGE))
		}
		protected function init()
		{				
			
		}
		protected function FBResponse(method:String,value:*)
		{	
			
			log+="METHOD "+method+"   ";
			switch(method)
			{
				case FBMethod.STATUS:
					setStatus(value);
					
					break;
				case FBMethod.USER_INFO:
					
					setUserInfo(value);
					
					break;
				case FBMethod.PROFILE_PIC:
					setImage(value);
					
					break;
				default:
					break;
			}	
			dispatchEvent(new Event(Event.CHANGE))
		}
		private function setUserInfo(response:*)
		{
			log+="USER INFO PROSS ";
			User.userData(response);			
		}
		private function setImage(link:String)
		{
			User.setImage(link);
		}
		private function setStatus(response:*)
		{			
			if(response.status=="connected")
			{
				_logged=true;
				User.login(UserTypes.FACEBOOK)
			}
			else if(response.status=="not_authorized")
			{
				_logged=false;
				ExternalInterface.call("logmein");
			}
			else
			{
				_logged=false;
				User.logout();
			}
		}
		
	}
}